package com.magictower.primary.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;

import com.magictower.primary.activity.EnterPwdActivity;
import com.magictower.primary.db.dao.AppLockDao;

import java.util.List;

/**
 * @author kejunzhan
 * @since 2017/12/19
 */

public class WatchDogService extends Service {

    private String tempStopPretectPackageName;
    private boolean flag = false;//标记当前的看萌狗是否停下来
    private ActivityManager am;
    private List<String> list;
    private WatchDogReceiver receiver;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        AppLockDao dao = new AppLockDao(this);
        list = dao.findAll();
        //注册广播接收者
        receiver = new WatchDogReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.itheima.mobileguard.stopprotect");
        /**
         * 当屏幕锁住的时候。狗就休息
         * 屏幕解锁的时候。让狗活过来
         */
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(receiver, filter);

        //获取到进程管理器
        am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        /*
        1.首先获取到当前的任务栈
        2.取任务栈中最顶的任务
         */
        startWatDog();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        flag = false;
        //注销广播
        unregisterReceiver(receiver);
        receiver = null;
    }

    private class WatchDogReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.itheima.mobileguard.stopprotect".equals(intent.getAction())) {
                //获取到停止保护的对象
                tempStopPretectPackageName = intent.getStringExtra("packageName");
            } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                //让狗休息
                tempStopPretectPackageName = null;
                flag = false;
            } else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
                //让狗继续干活
                if (!flag) {
                    startWatDog();
                }
            }
        }
    }

    private void startWatDog() {
        new Thread() {
            @Override
            public void run() {
                flag = true;
                while (flag) {
                    /*
                    由于狗一直在后台运行，为了避免程序阻塞
                    获取到当前正在运行的任务栈
                     */
                    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
                    ActivityManager.RunningTaskInfo task = tasks.get(0);
                    String packageName = task.topActivity.getPackageName();
                    System.out.println("packageName: "+ packageName);
                    SystemClock.sleep(30);

                    /*
                    直接在数据库中查询数据
                    这个可以优化，改为内存当中寻找
                     */
                    if (list.contains(packageName)) {
                        //说明需要临时取消保护
                        //是因为用户输入了正确的密码
                        if (packageName.equals(tempStopPretectPackageName)) {
                            System.out.println("不需要进行密码输入");
                        } else {
                            System.out.println("需要进行密码输入");
                            Intent intent = new Intent(WatchDogService.this, EnterPwdActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("packageName", packageName);
                            startActivity(intent);
                        }
                    }
                }
            }
        }.start();
    }
}
